package com.xbongbong.paas.help;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.GaodeGeoHelper;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ProErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;

import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/06/21 16:50
 */
public class AddressHelp {

    /**
     * 高德解析地址
     * @param value
     * @param fieldAttrEntity
     * @return
     * @throws XbbException
     */
    public static JSONObject getAddress(String value, FieldAttrEntity fieldAttrEntity) throws XbbException {
        JSONObject result = new JSONObject();
        try {
            JSONObject address = GaodeGeoHelper.geo(value, "");
            if (Objects.isNull(address)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100080);
            }
            String province = address.getString(BusinessConstant.PROVINCE);
            String city = address.getString(BusinessConstant.CITY);
            String district = address.getString(BusinessConstant.DISTRICT);
            String detailAddress = value.replaceAll(province, "").replaceAll(city, "").replace(district, "");
            result.put(BusinessConstant.PROVINCE, province);
            result.put(BusinessConstant.CITY, city);
            result.put(BusinessConstant.DISTRICT, district);
            if (Objects.equals(1, fieldAttrEntity.getShowDetailAddress())) {
                result.put(BusinessConstant.ADDRESS, detailAddress);
            } else {
                result.put(BusinessConstant.ADDRESS, "");
            }

        } catch (Exception e) {
            throw new XbbException(ProErrorCodeEnum.API_ERROR_260019);
        }
        return result;
    }
}
